<template>
  <div class="page-container" v-global-loading="loading">
    <div class="page-card-container">
      <div
        style="
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
        "
      >
        <a-input-search
          allowClear
          v-model:value="pageSet.name"
          placeholder="请输入分类名称"
          enter-button
          @search="loadPagination(true)"
          style="width: 300px"
        />
        <div
          class="commonBtn-primary"
          @click="addform(1)"
          style="min-width: 60px"
        >
          新建
        </div>
      </div>
      <a-table
        size="small"
        :loading="tableLoading"
        :dataSource="tableData"
        :columns="columns"
        bordered
        :pagination="false"
        row-key="id"
        :scroll="{
          x: 1200,
          y: useAppStore.pageCommonInfo.canUseHeight - 36 + 'px'
        }"
      >
        <template #bodyCell="{text, record, index, column}">
          <template v-if="column.title == '分类名称'">
            <span></span>
          </template>
          <template v-if="column.title == '一级分类图标'">
            <div
              class="pointer"
              v-if="text"
              @click="
                () => {
                  setVisible(true, index);
                }
              "
            >
              <img :src="text" alt="" style="height: 30px" />
              <a-image
                :width="0"
                :style="{display: 'none'}"
                :preview="{
                  visible: visibleImg[index],
                  onVisibleChange: (e) => {
                    setVisible(e, index);
                  }
                }"
                :src="text"
              />
            </div>
          </template>
          <template v-if="column.title == '背景图'">
            <div
              class="pointer"
              v-if="text"
              @click="
                () => {
                  setVisible1(true, index);
                }
              "
            >
              <img :src="text" alt="" style="height: 30px" />
              <a-image
                :width="0"
                :style="{display: 'none'}"
                :preview="{
                  visible: visibleImg1[index],
                  onVisibleChange: (e) => {
                    setVisible1(e, index);
                  }
                }"
                :src="text"
              />
            </div>
          </template>
          <template v-if="column.title == '操作'">
            <div>
              <span
                class="pointer c-primaryColor"
                onselectstart="return false"
                @click="compile(1, record.id)"
                >&nbsp;&nbsp;编辑</span
              >
              <span
                class="pointer c-primaryColor"
                onselectstart="return false"
                @click="compile(2, record.id)"
                >&nbsp;&nbsp;删除</span
              >
              <span
                class="pointer c-primaryColor"
                onselectstart="return false"
                @click="compile(3, record.id, record.status)"
                >&nbsp;&nbsp;{{ record.status == 1 ? "禁用" : "启用" }}</span
              >
              <span
                class="pointer c-primaryColor"
                onselectstart="return false"
                @click="compile(4, record.id)"
                v-if="!record.isHide"
                >&nbsp;&nbsp;推荐首页</span
              >
            </div>
          </template>
        </template>
        <template #expandIcon="props">
          <div style="display: flex; justify-content: left">
            <div
              v-if="props.record.children.length || props.record.parentId == 0"
              style="margin-right: 10px"
              @click="
                (e) => {
                  props.onExpand(props.record, e);
                }
              "
            >
              <div
                :class="props.expanded ? 'cartoon' : ''"
                style="transition: all 0.2s; cursor: pointer"
              >
                <RightOutlined />
              </div>
            </div>
            <div v-else style="margin-right: 10px"></div>
            {{ props.record.name }}
          </div>
        </template>
      </a-table>
      <Pagination
        :pageSet="pageSet"
        style="margin-top: 10px"
        :loadPagination="loadPagination"
      ></Pagination>
      <a-modal
        v-model:open="visible"
        width="800px"
        :title="title"
        :footer="null"
        :maskClosable="false"
        :destroyOnClose="true"
        @cancel="addform(2)"
      >
        <div v-global-loading="modalloading">
          <a-form :labelCol="{span: 6}" :model="form" ref="formRef">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="分类名称"
                  name="name"
                  :rules="[{required: true, message: '请填写'}]"
                >
                  <a-input v-model:value="form.name" />
                </a-form-item>
                <a-form-item label="是否启用" name="status">
                  <a-radio-group v-model:value="form.status" name="radioGroup">
                    <a-radio :value="1">启用</a-radio>
                    <a-radio :value="0">停用</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item
                  label="一级分类图标"
                  name="oneFileUrl"
                  v-if="!form.parentId"
                  :rules="[{required: true, message: '请上传图标'}]"
                  :labelCol="{span: 8}"
                >
                  <div
                    style="
                      width: 100px;
                      height: 100px;
                      border: 1px solid rgb(211, 211, 211);
                      border-radius: 10px;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                      cursor: pointer;
                    "
                    v-if="!form.oneFileUrl"
                    @click="upload(1)"
                  >
                    <CloudUploadOutlined
                      style="color: rgb(214, 208, 208); font-size: 60px"
                    />
                  </div>
                  <img
                    :src="form.oneFileUrl"
                    @click="upload(1)"
                    style="height: 100px; cursor: pointer"
                    alt=""
                    v-else
                  />
                </a-form-item>
                <a-form-item
                  label="涨幅比例（%）"
                  name="discount"
                  :labelCol="{span: 8}"
                  v-show="form.level == 3"
                >
                  <a-input-number
                    v-model:value="form.discount"
                    :min="0"
                    style="width: 100%"
                  />
                </a-form-item>
                <a-form-item label="排序" name="sort">
                  <a-input v-model:value="form.sort" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="父级" name="parentId">
                  <a-tree-select
                    v-model:value="form.parentId"
                    show-search
                    :dropdown-style="{maxHeight: '400px', overflow: 'auto'}"
                    allow-clear
                    tree-default-expand-all
                    :tree-data="treeData"
                    :fieldNames="{value: 'id', label: 'name'}"
                    tree-node-filter-prop="name"
                    @select="onSelect"
                  >
                  </a-tree-select>
                </a-form-item>
                <a-form-item label="是否显示首页" name="isHide">
                  <a-radio-group v-model:value="form.isHide" name="radioGroup">
                    <a-radio :value="true">是</a-radio>
                    <a-radio :value="false">否</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item
                  label="背景图"
                  name="backgroundImg"
                  :labelCol="{span: 8}"
                >
                  <div
                    style="
                      width: 100px;
                      height: 100px;
                      border: 1px solid rgb(211, 211, 211);
                      border-radius: 10px;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                      cursor: pointer;
                    "
                    v-if="!form.backgroundImg"
                    @click="upload(2)"
                  >
                    <CloudUploadOutlined
                      style="color: rgb(214, 208, 208); font-size: 60px"
                    />
                  </div>
                  <img
                    :src="form.backgroundImg"
                    @click="upload(2)"
                    style="height: 100px; cursor: pointer"
                    alt=""
                    v-else
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <div style="display: flex; justify-content: end">
            <a-button style="margin-right: 14px" @click="addform(2)"
              >取消</a-button
            >
            <a-button type="primary" @click="addform(3)">确定</a-button>
          </div>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {ref, inject, onActivated, onMounted} from "vue";
import Pagination from "@/components/pagination/Pagination.vue";
import {message, Modal} from "ant-design-vue";
import {
  productTypePage,
  productTypeCreate,
  productTypeUpdate,
  productTypeChangeStatus,
  productTypeDelete,
  productTypeSetIsHide,
  productTypeDetail,
  productTypeList
} from "@/api/merchandise/classification";
import useAppStore from "@/store/app";
import {trigerUpload, trigerUploadObs} from "@/utils/common";
const filterOption = (input: string, option: any) => {
  return option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const onSelect = (_, node) => {
  // 根据选择父节点，赋值当前要操作的树等级
  form.value.level = node.level * 1 + 1;
};
const calcCanUseHeight: any = inject("calcCanUseHeight");
onActivated(() => {
  calcCanUseHeight();
});
onMounted(() => {
  calcCanUseHeight();
});
const visibleImg1 = ref<any>([]);
const setVisible1 = (flag, index) => {
  visibleImg1.value[index] = flag;
};
const visibleImg = ref<any>([]);
const setVisible = (flag, index) => {
  visibleImg.value[index] = flag;
};
const upload = async (type) => {
  const fileInfo: any = await trigerUpload();
  let files = fileInfo.target.files[0];
  if (
    files.type == "image/jpeg" ||
    files.type == "image/png" ||
    files.type == "image/jpg"
  ) {
    modalloading.value = true;
    trigerUploadObs(fileInfo)
      .then((res) => {
        if (type == 1) {
          form.value.oneFileUrl = res;
        } else {
          form.value.backgroundImg = res;
        }
      })
      .finally(() => {
        modalloading.value = false;
      });
  } else {
    message.error("请上传jpeg、png、jpg类型的图片");
  }
};
const formRef = ref();
const visible = ref(false);
const title = ref("新建");
const form = ref<any>({});
const modalloading = ref(false);
const tableLoading = ref<boolean>(false);
const loading = ref<boolean>(false);
const pageSet = ref<any>({
  pageNo: 1,
  pageSize: 20,
  total: 0
});
const treeData = ref([]);
const gettreeData = () => {
  productTypeList().then((res) => {
    treeData.value = getHierarchy1(res.data);
  });
};
const tableData = ref<Array<object>>([]);
//新建
const addform = (type: number) => {
  if (type == 1) {
    form.value = {};
    gettreeData();
    visible.value = true;
  } else if (type == 2) {
    formRef.value.clearValidate();
    visible.value = false;
  } else if (type == 3) {
    formRef.value.validate().then(() => {
      let formData = JSON.parse(JSON.stringify(form.value));
      modalloading.value = true;
      if (formData.id) {
        //编辑
        if (!formData.parentId) {
          formData.parentId = 0;
        }
        productTypeUpdate(formData)
          .then(() => {
            message.success("编辑成功!");
            visible.value = false;
            loadPagination();
          })
          .finally(() => {
            modalloading.value = false;
          });
      } else {
        //创建
        if (!formData.parentId) {
          formData.parentId = 0;
        }
        productTypeCreate(formData)
          .then(() => {
            message.success("创建成功!");
            visible.value = false;
            loadPagination();
          })
          .finally(() => {
            modalloading.value = false;
          });
      }
    });
  }
};
//操作
const compile = (type: number, id: string | number, status?: number) => {
  if (type == 1) {
    //编辑
    gettreeData();
    loading.value = true;
    productTypeDetail({id})
      .then((res) => {
        form.value = res.data;
        if (form.value.parentId == 0) {
          form.value.parentId = null;
        }
        visible.value = true;
      })
      .finally(() => {
        loading.value = false;
      });
  } else if (type == 2) {
    //删除
    Modal.confirm({
      title: "确定要删除这条数据吗？",
      onOk() {
        loading.value = true;
        productTypeDelete({id})
          .then(() => {
            message.success("删除成功！");
            loadPagination(true);
          })
          .finally(() => {
            loading.value = false;
          });
      }
    });
  } else if (type == 3) {
    //修改状态
    loading.value = true;
    let a = status == 1 ? 0 : 1;
    productTypeChangeStatus({id, status: a})
      .then(() => {
        message.success("修改成功!");
        loadPagination();
      })
      .finally(() => {
        loading.value = false;
      });
  } else if (type == 4) {
    loading.value = true;
    productTypeDetail({id})
      .then((res) => {
        let formData = res.data;
        formData.isHide = true;
        productTypeSetIsHide(formData)
          .then(() => {
            message.success("设置成功");
            loadPagination();
          })
          .finally(() => {
            loading.value = false;
          });
      })
      .catch(() => {
        loading.value = false;
      });
  }
};
//获取数据
const loadPagination = (flag: boolean = false): void => {
  if (flag) {
    pageSet.value.pageNo = 1;
  }
  tableLoading.value = true;
  productTypePage(pageSet.value)
    .then((res) => {
      tableData.value = getHierarchy(res.data.rows);
      pageSet.value.total = res.data.totalRows;
    })
    .finally(() => {
      tableLoading.value = false;
    });
};
loadPagination();
const getHierarchy = (list: any = []) => {
  let listData = JSON.parse(JSON.stringify(list));
  const go = (data, a) => {
    data.forEach((item) => {
      item.hierarchy = a;
      if (item.children.length) {
        go(item.children, ++a);
      }
    });
  };
  listData.forEach((item) => {
    item.hierarchy = 1;
    if (item.children.length) {
      go(item.children, 2);
    }
  });
  return listData;
};
const getHierarchy1 = (list: any = []) => {
  let listData = JSON.parse(JSON.stringify(list));
  listData.forEach((item) => {
    item.children.forEach((v) => {
      v.children = [];
    });
  });
  return listData;
};
//重置
const reset = (): void => {
  pageSet.value = {
    pageNo: 1,
    pageSize: 20,
    total: 0
  };
  loadPagination(true);
};
const columns = ref<Array<object>>([
  {
    title: "分类名称",
    dataIndex: "name",
    align: "center",
    width: 200
  },
  {
    title: "一级分类图标",
    dataIndex: "oneFileUrl",
    align: "center",
    width: 150
  },
  {
    title: "背景图",
    dataIndex: "backgroundImg",
    align: "center",
    width: 150
  },
  // {
  //   title: "商品编码",
  //   dataIndex: "code",
  //   align: "center",
  //   width: 200
  // },
  // {
  //   title: "备注",
  //   dataIndex: "remark",
  //   align: "center",
  //   width: 200
  // },
  {
    title: "是否显示首页",
    dataIndex: "isHide",
    align: "center",
    width: 200,
    customRender: ({text}) => {
      return text ? "是" : "否";
    }
  },
  {
    title: "涨幅比例",
    dataIndex: "discount",
    align: "center",
    width: 100,
    customRender: ({text}) => {
      return text ? text + "%" : "";
    }
  },
  {
    title: "排序",
    dataIndex: "sort",
    align: "center",
    width: 200
  },
  {
    title: "状态",
    dataIndex: "status",
    align: "center",
    width: 120,
    customRender: ({text}) => {
      return text == 1 ? "启用" : "停用";
    }
  },
  {
    title: "操作",
    dataIndex: "a",
    align: "center",
    width: 200,
    fixed: "right"
  }
]);
</script>

<style lang="less" scoped>
.cartoon {
  transform: rotate(90deg);
}
</style>
